
import {
    AppName
}
from '../app.config.js';
import fs from 'fs';
import path, {
    join
}
from 'path';

/*
数据封装
 */
class XiuxianData {
    constructor() {
        //获取配置文件参数

        //文件路径参数
        //插件根目录
        const __dirname =
            path.resolve() + path.sep + 'plugins' + path.sep + AppName;
        this.filePathMap = {
            player: path.join(__dirname, '/resources/data/mz_player'), //用户数据
            najie: path.join(__dirname, '/resources/data/mz_najie'),
            lib: path.join(__dirname, '/resources/data/item'),
        };
        this.lib_path = this.filePathMap.lib;
        //加载人生列表
        this.rensheng_list = JSON.parse(
                fs.readFileSync(`${this.lib_path}/人生.json`));
        
    }

    /**
     * 检测存档存在
     * @param file_path_type ["player" , "association","tudi" ]
     * @param file_name
     */
    existData(file_path_type, file_name) {
        let file_path;
        file_path = this.filePathMap[file_path_type];
        let dir = path.join(file_path + '/' + file_name + '.json');
        if (fs.existsSync(dir)) {
            return true;
        }
        return false;
    }

    /**
     * 获取文件数据(user_qq为空查询item下的file_name文件)
     * @param file_name  [player,equipment,najie,tudi]
     * @param user_qq
     */
    getData(file_name, user_qq) {
        let file_path;
        let dir;
        let data;
        if (user_qq) {
            //带user_qq的查询数据文件
            file_path = this.filePathMap[file_name];
            dir = path.join(file_path + '/' + user_qq + '.json');
        } else {
            //不带参数的查询item下文件
            file_path = this.filePathMap.lib;
            dir = path.join(file_path + '/' + file_name + '.json');
        }
        try {
            data = fs.readFileSync(dir, 'utf8');
        } catch (error) {
            logger.error('读取文件错误：' + error);
            return 'error';
        }
        //将字符串数据转变成json格式
        data = JSON.parse(data);
        return data;
    }

    /**
     * 写入数据
     * @param file_name [player,equipment,najie]
     * @param user_qq
     * @param data
     */
    setData(file_name, user_qq, data) {
        let file_path;
        let dir;
        if (user_qq) {
            file_path = this.filePathMap[file_name];
            dir = path.join(file_path + '/' + user_qq + '.json');
        } else {
            file_path = this.filePathMap.lib;
            dir = path.join(file_path + '/' + file_name + '.json');
        }
        let new_ARR = JSON.stringify(data, '', '\t'); //json转string
        if (fs.existsSync(dir)) {
            fs.writeFileSync(dir, new_ARR, 'utf-8', err => {
                console.log('写入成功', err);
            });
        }
        return;
    }
    }
export default new XiuxianData();
